package com.example.community.controller;

import com.example.community.dto.AccessTokenDTO;
import com.example.community.dto.UserDto;
import com.example.community.model.GiteeUser;
import com.example.community.provider.AliyunOssProvider;
import com.example.community.provider.GiteeProvider;
import com.example.community.provider.UFileResult;
import com.example.community.service.GiteeUserService;
import com.example.community.strategy.LoginUserInfo;
import com.example.community.strategy.UserStrategy;
import com.example.community.strategy.UserStrategyFactory;
import com.example.community.util.GetIpAddress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
@Slf4j
public class AuthorizeController {
    @Autowired
    private GiteeProvider giteeProvider;

    @Autowired
    GiteeUserService gtieeUserService;

    @Autowired
    private AliyunOssProvider aliyunOssProvider;

    @Autowired
    UserStrategyFactory userStrategyFactory;

    @Value("${gitee.oauth.client_id}")
    private String clientId;
    @Value("${gitee.oauth.client_secret}")
    private String clientSecret;
    @Value("${gitee.oauth.redirect_url}")
    private String redirectUrl;

    @GetMapping("/callback/{type}")
    public String newCallback(@PathVariable(name = "type") String type,
                              @RequestParam(name = "code") String code,
                              @RequestParam(name = "state", required = false) String state,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        UserStrategy userStrategy = userStrategyFactory.getStrategy(type);
        LoginUserInfo loginUserInfo = userStrategy.getUser(code, state);
        if (loginUserInfo != null && loginUserInfo.getId() != null) {
            GiteeUser giteeUser = new GiteeUser();
            String token = UUID.randomUUID().toString();
            giteeUser.setToken(token);
            giteeUser.setName(loginUserInfo.getName());
            giteeUser.setAccountId(String.valueOf(loginUserInfo.getId()));
            giteeUser.setType(type);
            UFileResult fileResult = null;
            try {
                fileResult = aliyunOssProvider.upload(loginUserInfo.getAvatarUrl());
                giteeUser.setAvatarUrl(fileResult.getFileUrl());
            } catch (Exception e) {
                giteeUser.setAvatarUrl(loginUserInfo.getAvatarUrl());
            }
            giteeUser.setIp(GetIpAddress.getIp(request));
            gtieeUserService.createOrUpdate(giteeUser);
            Cookie cookie = new Cookie("token", "GU" + token);
            cookie.setMaxAge(60 * 60 * 24 * 15);
            cookie.setPath("/");
            response.addCookie(cookie);
            return "redirect:/";
        } else {
            log.error("callback get github error,{}", loginUserInfo);
            // 登录失败，重新登录
            return "redirect:/";
        }
    }

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           HttpServletRequest request,
                           HttpServletResponse response){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setRedirect_url(redirectUrl);
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        UserDto giteeUserDto = giteeProvider.getUser(accessToken);

        if (giteeUserDto != null){

            GiteeUser giteeUser = new GiteeUser();
            giteeUser.setName(giteeUserDto.getName());
            giteeUser.setAccountId(String.valueOf(giteeUserDto.getId()));
            String token = UUID.randomUUID().toString();
            giteeUser.setToken(token);
            UFileResult fileResult = null;
            giteeUser.setBio(giteeUserDto.getBio());
            giteeUser.setAvatarUrl(giteeUserDto.getAvatarUrl());
            giteeUser.setIp(GetIpAddress.getIp(request));
            gtieeUserService.createOrUpdate(giteeUser);
            giteeUserDto.setUserType(1);
            Cookie cookie = new Cookie("token", "GU" + token);
            cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
            response.addCookie(cookie);
            request.getSession().setAttribute("user", giteeUserDto);

            return "redirect:";
        }else {
            return "redirect:";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
